package com.egao.common.core.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.io.UnsupportedEncodingException;

/**
 * excel工具类
 *
 * @author lym
 */
public class ExcelUtils {

    /**
     * 根据列最大值自适应列宽
     *
     * @param sheet sheet
     */
    public static void autoColumnMaxSizeAll(Sheet sheet) {
        int num = sheet.getFirstRowNum();
        if (num == 0) {
            return;
        }
        int maxColumn = sheet.getRow(0).getPhysicalNumberOfCells();
        try {
            TimeInterval timer = DateUtil.timer();
            //列宽自适应，只对英文和数字有效
            for (int i = 0; i <= maxColumn; i++) {
                sheet.autoSizeColumn(i);
            }
            //获取当前列的宽度，然后对比本列的长度，取最大值
            for (int columnNum = 0; columnNum <= maxColumn; columnNum++) {
                int columnWidth = sheet.getColumnWidth(columnNum) / 256;
                for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
                    Row currentRow;
                    //当前行未被使用过
                    if (sheet.getRow(rowNum) == null) {
                        currentRow = sheet.createRow(rowNum);
                    } else {
                        currentRow = sheet.getRow(rowNum);
                    }

                    if (currentRow.getCell(columnNum) != null) {
                        Cell currentCell = currentRow.getCell(columnNum);
                        int length = currentCell.toString().getBytes("GBK").length;
                        if (columnWidth < length + 1) {
                            columnWidth = length + 1;
                        }
                    }
                }

                columnWidth = columnWidth * 256;
                if (columnWidth < 15000) {
                    sheet.setColumnWidth(columnNum, columnWidth);
                } else {
                    sheet.setColumnWidth(columnNum, 15000);
                }
            }
            System.out.println("自适应列宽耗时：" + timer.interval() + " 毫秒");
        } catch (UnsupportedEncodingException e) {
            // 转换异常 列宽自适应失败 直接退出 直接忽略
            return;
        }
    }


}
